<template>
  <a-select
    v-if="multiple"
    v-model:value="selectValue"
    style="width: 100%"
    mode="multiple"
    :placeholder="placeholder"
    :options="options"
    :field-names="fieldNames"
    :show-arrow="true"
    :disabled="disabled"
    :get-popup-container="getPopupContainer"
    @change="handleChange"
  ></a-select>
  <a-select
    v-else
    v-model:value="selectValue"
    style="width: 100%"
    :allow-clear="allowClear"
    :placeholder="placeholder"
    :options="options"
    :field-names="fieldNames"
    :show-arrow="true"
    :disabled="disabled"
    :get-popup-container="getPopupContainer"
    @change="handleChange"
  ></a-select>
</template>

<script lang="ts" setup>
import { ref, watch, withDefaults, toRef } from 'vue'
import { dictQueryByFlag } from '@/api/dict'

const emits = defineEmits(['update:value', 'update:name', 'loadDictData', 'change'])

// const { placeholder, value, flag, valueKey, appCode, multiple, isHttp, dataList, disabled, allowClear } = withDefaults(
const props = withDefaults(
  defineProps<{
    placeholder?: string // 提示
    value: any // 绑定的值
    name?: any // 绑定的值
    flag?: string // 字典标识
    valueKey?: string // 值的key
    appCode?: string // 字典所属应用编码
    multiple?: boolean // 是否多选
    dataList?: Array<any> // 字典数据列表
    isHttp?: boolean // 是否通过http请求获取数据
    disabled?: boolean // 是否停用
    allowClear?: boolean // 是否允许清空
    getPopupContainer?: any
  }>(),
  {
    flag: '',
    valueKey: 'value',
    multiple: false,
    isHttp: true,
    dataList: () => [],
    disabled: false,
    allowClear: true,
    getPopupContainer: undefined
  }
)

let options = ref<any[]>([])
const selectValue = ref<any>(props.value)
// const dataListRef = toRef(props, 'dataList')

watch(
  () => props.value,
  (newVal) => {
    if (JSON.stringify(newVal) === JSON.stringify(selectValue.value)) {
      return
    }
    selectValue.value = newVal
  }
)

const fieldNames = {
  label: props.isHttp ? 'name' : 'label',
  value: props.isHttp ? props.valueKey : 'value'
}

if (props.isHttp) {
  dictQueryByFlag({
    flag: props.flag,
    appCode: props.appCode
  }).then((res) => {
    options.value = res[props.flag]
    if (options.value) {
      emits('loadDictData', {
        map: (() => {
          const map = {}
          options.value.forEach((item) => {
            map[item.name] = item[props.valueKey]
          })
          return map
        })(),
        arr: options.value
      })
    }
  })
} else {
  options = toRef(props, 'dataList')
}

const formatData = (data, key) => {
  if (typeof data === 'string') {
    const item = options.value.find((item) => item[fieldNames.value] === data)
    return item ? item[key] : undefined
  } else if (typeof data === 'object') {
    const arr: string[] = []
    data.forEach((el) => {
      const item = options.value.find((obj) => obj[fieldNames.value] === el)
      if (item) {
        arr.push(item[key])
      }
    })
    return arr
  }
}

const handleChange = (e) => {
  emits('update:value', e)
  const name = formatData(e, fieldNames.label)
  const dictDataIds = formatData(e, 'dictDataId')
  emits('update:name', name)
  emits('change', dictDataIds)
}
</script>

<style lang="less"></style>
